<?php

require_once("config/wh_config.php");
require_once("core/wh_document.php");
require_once("core/wh_plugin.php");
require_once("core/wh_tools.php");

$wh_ImportPlugins = array(); ///< Importer plugins list
$wh_ModifyPlugins = array(); ///< Modifier plugins list
$wh_ExportPlugins = array(); ///< Exporter plugins list

//------------------------------------------------------------------------------
// Initialize

$posted = WH_GetVar(WH_POST, "posted", 0); 

// Input data type
$input_type = WH_GetVar(WH_POST, "input_type", "raw"); 

// Output data type
$output_type = WH_GetVar(WH_POST, "output_type", array("code")); 

// Output file type
$output_file = WH_GetVar(WH_POST, "output_file", ""); 

// Input data
if($input_type == "raw")
{
	$text = WH_GetVar(WH_POST, "input_data", "i-t:f-=s i-i-w-i-A-A52 r:n:n G14&X1-B1-=s"); 
}
else // if($input_type == "file")
{
	if(isset($_FILES["input_file"]))
	{
		$input_file = $_FILES["input_file"]["tmp_name"];
		$text = file_get_contents($input_file);
	}
}

// Langage
$lang = WH_GetVar(WH_POST, "lang", "fr");
	
// Importer class
$wh_Importer = WH_GetVar(WH_POST, "importer", "MdC88");
	
// Modifier class list
$wh_Modifier = WH_GetVar(WH_POST, "modifier", array());

// Exporter class
$wh_Exporter = WH_GetVar(WH_POST, "exporter", "HWXml");

// Build plugin list		
$fileList = array();
if($dh = opendir($wh_PluginRootDir))
{
	while(($file = readdir($dh)) !== false)
	{
		if(substr($file, -strlen($wh_PluginExtension)) == $wh_PluginExtension)
			$fileList[] = $file; // get all plugins scripts
	}
	closedir($dh);

	if(sizeof($fileList) != '0') // sort list
		sort($fileList);

	foreach($fileList as &$file)
	{
		require_once($wh_PluginRootDir."/".$file);
		$className = substr($file, 0, strlen($file) - strlen($wh_PluginExtension));
		if(WH_CallStatic($className, "CanImport"))
		{
			$plugin = new $className();
			WH_SetupPluginVars($plugin, $className, WH_Plugin::TypeImporter);
			$wh_ImportPlugins[$plugin->GetId()] = array("class" => $plugin, "name" => $className);
		}
		if(WH_CallStatic($className, "CanModify"))
		{
			$plugin = new $className();
			WH_SetupPluginVars($plugin, $className, WH_Plugin::TypeModifier);
			$wh_ModifyPlugins[$plugin->GetId()] = array("class" => $plugin, "name" => $className);
		}
		if(WH_CallStatic($className, "CanExport"))
		{
			$plugin = new $className();
			WH_SetupPluginVars($plugin, $className, WH_Plugin::TypeExporter);
			$wh_ExportPlugins[$plugin->GetId()] = array("class" => $plugin, "name" => $className);
		}
	}
}

//------------------------------------------------------------------------------
// Import

$start_time = microtime(true); 

// Create import plugin
$imp = $wh_ImportPlugins[$wh_Importer]["class"];
// Import data and create document
$doc = $imp->Import($text);

$time_import = sprintf("%0.3f sec", microtime(true) - $start_time);

//------------------------------------------------------------------------------
// Modify

$start_time = microtime(true); 

foreach ($wh_Modifier as $modName)
{
	$mod = $wh_ModifyPlugins[$modName]["class"];
	$doc = $mod->Modify($doc);
}

$time_modify = sprintf("%0.3f sec", microtime(true) - $start_time);

//------------------------------------------------------------------------------
// Export

$start_time = microtime(true); 

// Create export plugin
$exp = $wh_ExportPlugins[$wh_Exporter]["class"];
// Exporter
$code = $exp->Export($doc);

$time_export = sprintf("%0.3f sec", microtime(true) - $start_time);




//------------------------------------------------------------------------------

/***/
function WH_SetupPluginVars(&$plugin, $pluginName, $pluginType)
{
	global $posted;
	
	switch($pluginType)
	{
	case WH_Plugin::TypeImporter: $pluginTypeName = "importer"; break;
	case WH_Plugin::TypeModifier: $pluginTypeName = "modifier"; break;
	case WH_Plugin::TypeExporter: $pluginTypeName = "exporter"; break;
	}

	// Setup variables
	foreach($plugin->GetVariables() as $var)
	{
		$default = $var->GetValue();
		if($posted && $var->GetType() == WH_Variable::Boolean)
			$default = false;
		$value = WH_GetVar(WH_POST, "{$pluginTypeName}_var_".WH_CallStatic($pluginName, "GetId")."_{$var->GetName()}", $default);
		$plugin->SetVariable($var->GetName(), $value);
	}
}

/***/
function WH_BuildPluginDesc(&$plugin, $pluginType)
{
	global $wh_Importer, $wh_Modifier, $wh_Exporter;
	
	$flag = "";
	$type = "radio";
	switch($pluginType)
	{
	case WH_Plugin::TypeImporter: 
		$name = $pluginTypeName = "importer";
		if($plugin["class"]->GetId() == $wh_Importer)
			$flag = "checked";
		break;
	case WH_Plugin::TypeModifier:
		$pluginTypeName = "modifier";
		$name = "modifier[]";
		if(in_array($plugin["class"]->GetId(), $wh_Modifier))
			$flag = "checked";
		$type = "checkbox";
		break;
	case WH_Plugin::TypeExporter:
		$name = $pluginTypeName = "exporter";
		if($plugin["class"]->GetId() == $wh_Exporter)
			$flag = "checked";
		break;
	}
	echo "<input type='$type' name='$name' value='{$plugin["class"]->GetId()}' $flag onClick='WH_Unroll(\"{$pluginTypeName}\", \"{$plugin["class"]->GetId()}\")' />\n";
	echo "<span title='{$plugin["class"]->GetDesc($pluginType)}'>{$plugin["class"]->GetName()}</span>\n";
	echo "<div><div class='{$pluginTypeName}_desc' id='{$pluginTypeName}_desc_{$plugin["class"]->GetId()}' style='border:darkgray 1px solid; padding:0.2em; margin:0.2em;'>\n";
	echo "<span style='font-weight:bold;'>{$plugin["class"]->GetDesc($pluginType)}</span><br/>\n";
	echo "<span style='font-size:small;'>Version {$plugin["class"]->GetVersion()}</span><br/>\n";
	echo "<span style='font-size:small;'>{$plugin["class"]->GetCredit()}</span><br/>\n";
	if(count($plugin["class"]->GetVariables()) > 0)
	{
		echo "<hr color='darkgray' size='1'><span>Parameters:</span>\n";
		echo "<table style='size:100%;'>\n";
		$count = 0;
		foreach($plugin["class"]->GetVariables() as $key => $var)
		{
			echo "<tr><td>&nbsp;&middot;&nbsp;$key</td><td>";
			$varName = "{$pluginTypeName}_var_{$plugin["class"]->GetId()}_$key";
			switch($var->GetType())
			{
			case WH_Variable::Boolean:
				echo "<input type='checkbox' name='$varName' id='$varName'";
				if($var->GetValue())
					echo " checked";
				echo " />";
				break;
			case WH_Variable::Integer:
			case WH_Variable::String:
				echo "<input type='text' name='$varName' value='{$var->GetValue()}' />";
				break;
			case WH_Variable::Enum:
				echo "<select name='$varName'>\n";
				foreach($var->GetEnum() as $enum)
				{
					echo "<option value='$enum'";
					if($var->GetValue() == $enum)
						echo " selected";
					echo ">$enum</option>\n";
				}
				echo "</select>\n";
				break;
			}
			echo "</td></tr>\n";
			$count++;
		}
		echo "</table>\n";
	}
	echo "</div></div>\n";
}


?>
<html>
	<head>
		<style>
			/* span:hover { border:red solid 1px; } */
			/* *.cell { border:#DDD solid 1px; padding:0.2em; } */
			tr { /*border: 1px blue solid;*/ vertical-align:top; }	
			/* td { border: 1px red solid; } */			
			/* table { border: 1px green solid; } */
		</style>
		<script language="JavaScript" type="text/javascript">

		function WH_InitPlugins(importer, exporter) 
		{
			WH_Unroll("importer", importer);
			WH_Unroll("exporter", exporter);
		}
		 
		function WH_HideDesc(cat) 
		{
			if(cat == "all")
			{
				WH_HideDesc("importer");
				WH_HideDesc("modifier");
				WH_HideDesc("exporter");
				return;
			}
			
			var descDiv;
			// iterate over all < div >-elements
			for(var i=0; descDiv = document.getElementsByTagName("div")[i]; i++ )
			{
			    // if found a plugin description
			    if(descDiv.className == cat + "_desc")
			    	descDiv.style.display = "none";
			}
		}
		 
		function WH_Unroll(cat, id) 
		{
			WH_HideDesc(cat);
		
			var descDiv = document.getElementById(cat + "_desc_" + id);
		    if(descDiv && descDiv.className == cat + "_desc")
		    	descDiv.style.display = "block";
		}
			
		function WH_SetBoolean(id) 
		{
			var tag = document.getElementById(id);
			//if(tag)
			{
		    	if(tag.checked)
		    		tag.value = "1";
		    	else
		    		tag.value = "0";
			}
		}
			
		function WH_ToggleVisibility(id) 
		{
			var tag = document.getElementById(id);
			if(tag)
			{
				if(tag.style.display == "none")
				{
					tag.style.display = tag.comment;
				}
				else
				{
					tag.comment = tag.style.display;
					tag.style.display = "none";
				}
			}
		}

		</script>
	</head>
	<body style="background-color:#DDD;" onLoad="<?php echo "WH_HideDesc('all'); WH_InitPlugins('{$imp->GetId()}', '{$exp->GetId()}'); WH_ToggleVisibility('debugWindow');"; ?>">

		<!-- Debug console -->
		<div id="debugToggle" style="float:right; cursor: pointer;" title="Debug window" onClick="WH_ToggleVisibility('debugWindow');">▼</div>
		<table cellpadding="0" cellspacing="0" style="padding:0; margin:0; width:100%;"><tr><td>

		<h2>WikiHiero <?php echo WH_GetVersion(); ?></h2>
		<form name="wh_form" action="index.php" method="post" enctype="multipart/form-data">
			<input type="hidden" name="posted" value="1">
			<input type="hidden" name="lang" value="<?php echo $lang; ?>">
			<h3 style="font-weight:bold;">Input</h3>
			<table style="border:solid 1px gray; background:lightgray; padding:1em; width:100%;">
				<tr>
					<td><input type="radio" name="input_type" value="raw" <?php if($input_type == "raw") echo "checked"; ?> />Text:</td>
					<td><textarea name="input_data" style="width:100%; height:100px;"><?php echo $text; ?></textarea></td>
				</tr>
				<tr>
					<td><input type="radio" name="input_type" value="file" <?php if($input_type != "raw") echo "checked"; ?> />File:</td>
					<td><input type="file" name="input_file" size="100" /></td>
				</tr>
			</table>
			<h3 style="font-weight:bold;">Process</h3>
			<table style="border:solid 1px gray; background:lightgray; padding:1em; width:100%;">
				<tr>
					<td style="width:33.33%;" class="cell">
						<h4>Importer:</h4>
						<?php
							foreach($wh_ImportPlugins as &$plugin)
								WH_BuildPluginDesc($plugin, WH_Plugin::TypeImporter);
						?>
					</td>
					<td style="width:33.33%;" class="cell">
						<h4>Modifier:</h4>
						<?php
							foreach($wh_ModifyPlugins as &$plugin)
								WH_BuildPluginDesc($plugin, WH_Plugin::TypeModifier);
						?>
					</td>
					<td style="width:33.33%;" class="cell">
						<h4>Exporter:</h4>
						<?php
							foreach($wh_ExportPlugins as &$plugin)
								WH_BuildPluginDesc($plugin, WH_Plugin::TypeExporter);
						?>
					</td>
				</tr>
			</table>
			<h3 style="font-weight:bold;">Output</h3>
			<table style="border:solid 1px gray; background:lightgray; padding:1em; width:100%;">
				<tr>
					<?php $flag = in_array("code", $output_type) ? "checked" :""; ?>
					<td><input type="checkbox" name="output_type[]" value="code" <?php echo $flag; ?> />Code</td>
					<td></td>
				</tr><tr>
					<?php $flag = in_array("inline", $output_type) ? "checked" :""; ?>
					<td><input type="checkbox" name="output_type[]" value="inline" <?php echo $flag; ?> />Inline</td>
					<td></td>
				</tr><tr>
					<?php $flag = in_array("file", $output_type) ? "checked" :""; ?>
					<td><input type="checkbox" name="output_type[]" value="file" <?php echo $flag; ?> />File:</td>
					<td><input type="text" name="output_file" size="100" value="<?php echo $output_file; ?>"/></td>
				</tr>
			</table>
			<br/>
			<input type="submit" value="Process"/>
		</form>
		<hr/>

		<h3 style="font-weight:bold;">Display</h3>
		<div style="border:solid 1px gray; background:lightgray; padding:1em;">
			<?php
				if(in_array("code", $output_type))
				{
					echo "<textarea style='width:100%; height:200px; background:#F0F0F0;' readonly>$code</textarea>";
				}
				if(in_array("inline", $output_type))
				{
					echo $code;
				}
				if(in_array("file", $output_type))
				{
					file_put_contents($output_file, $code);
				}
			?>
		</div>
		
		<div style="font-size:small; padding:1em;">
			<?php 
				echo "Import duration: $time_import<br/>";
				echo "Modify duration: $time_modify<br/>";
				echo "Export duration: $time_export<br/>";
				echo "<br/>";
				echo WH_GetCredit();
			?>
		</div>
		
		<!-- Debug console -->
		</td><td id="debugWindow" style="background:black; color:white;">
			<pre><?php 
				echo "Warning:\n".$wh_Warnings."\n";
				echo "\$_POST: "; 
				echo print_r($_POST); 
			?></pre>
		</td></tr></table>
	</body>
</html>